package com.data.modules.smzh.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.AutoLog;
import com.data.common.constant.MsgConstants;
import com.data.common.system.base.controller.BootController;
import com.data.common.system.query.QueryGenerator;
import com.data.common.system.vo.LoginUser;
import com.data.common.util.KamliClientUtil;
import com.data.modules.smzh.entity.Building;
import com.data.modules.smzh.entity.Project;
import com.data.modules.smzh.entity.SmComAnnouncement;
import com.data.modules.smzh.entity.SmzhScreenMsg;
import com.data.modules.smzh.service.IBuildingService;
import com.data.modules.smzh.service.IProjectService;
import com.data.modules.smzh.service.ISmzhScreenMsgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 智慧屏消息表
 * @Author: data-boot
 * @Date:   2023-01-06
 * @Version: V1.0
 */
@Api(tags="智慧屏消息表")
@RestController
@RequestMapping("/smzh/smzhScreenMsg")
@Slf4j
public class SmzhScreenMsgController extends BootController<SmzhScreenMsg, ISmzhScreenMsgService> {
	@Autowired
	private ISmzhScreenMsgService smzhScreenMsgService;

	@Autowired
	private IBuildingService buildingService;

	@Autowired
	private IProjectService projectService;

	/**
	 * 分页列表查询
	 *
	 * @param smzhScreenMsg
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "智慧屏消息表-分页列表查询")
	@ApiOperation(value="智慧屏消息表-分页列表查询", notes="智慧屏消息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SmzhScreenMsg smzhScreenMsg,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {


		QueryWrapper<SmzhScreenMsg> queryWrapper = QueryGenerator.initQueryWrapper(smzhScreenMsg, req.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(ObjectUtil.notEqual(sysUser.getUsername(),"admin")){
			queryWrapper.eq("create_by",sysUser.getUsername());
		}

		Page<SmzhScreenMsg> page = new Page<SmzhScreenMsg>(pageNo, pageSize);
		IPage<SmzhScreenMsg> pageList = smzhScreenMsgService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param smzhScreenMsg
	 * @return
	 */
	@AutoLog(value = "智慧屏消息表-添加")
	@ApiOperation(value="智慧屏消息表-添加", notes="智慧屏消息表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SmzhScreenMsg smzhScreenMsg) {

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(ObjectUtil.isNotEmpty(sysUser.getAppId())){
			smzhScreenMsg.setContent(sysUser.getAppId());
		}

		smzhScreenMsgService.save(smzhScreenMsg);

		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param smzhScreenMsg
	 * @return
	 */
	@AutoLog(value = "智慧屏消息表-编辑")
	@ApiOperation(value="智慧屏消息表-编辑", notes="智慧屏消息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SmzhScreenMsg smzhScreenMsg) {
		smzhScreenMsgService.updateById(smzhScreenMsg);

		//判断审核结果
		if(ObjectUtil.equals(1,smzhScreenMsg.getResult()) && ObjectUtil.isNotEmpty(smzhScreenMsg.getProjectNo())){

			List<String> projectlist = Arrays.asList(smzhScreenMsg.getProjectNo().split(","));

			//通过项目主键，查询出所有的建筑编号
			List<String> buildList = smzhScreenMsgService.queryBuildNoByProjectId(projectlist);

			buildList.stream().forEach(x->{
				String msgType = MsgConstants.SCREEN_MSG;
				List list = new ArrayList();

				Map<String,Object> map = new HashMap<>();
				map.put("title",smzhScreenMsg.getTitle());
				map.put("type",smzhScreenMsg.getType());
				map.put("content",smzhScreenMsg.getRemakr());
				list.add(map);

				if(ObjectUtil.equals(2,smzhScreenMsg.getMsgClass())){//智慧屏公告
					msgType = MsgConstants.NOTICE_MSG;
				}else if(ObjectUtil.equals(3,smzhScreenMsg.getMsgClass())){//文化专栏
					msgType = MsgConstants.CULTURE_MSG;
				}

				KamliClientUtil.doPostpushMsgUr(x,msgType,list);

			});

		}

		return Result.OK("操作成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "智慧屏消息表-通过id删除")
	@ApiOperation(value="智慧屏消息表-通过id删除", notes="智慧屏消息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		smzhScreenMsgService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "智慧屏消息表-批量删除")
	@ApiOperation(value="智慧屏消息表-批量删除", notes="智慧屏消息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.smzhScreenMsgService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	 @AutoLog(value = "推送小区公告信息")
	 @ApiOperation(value="推送小区公告信息", notes="推送小区公告信息")
	 @RequestMapping(value = "/push", method = RequestMethod.PUT)
	 public Result<?> push(@RequestBody JSONObject jsonObject) {

		 Boolean flag=true;

		 String msgType =MsgConstants.SCREEN_MSG;
		 String id =  jsonObject.getString("id");
		 List list = new ArrayList();
		 SmzhScreenMsg smzhScreenMsg = smzhScreenMsgService.getById(id);

		 Map<String,Object> map = new HashMap<>();
		 map.put("title",smzhScreenMsg.getTitle());
		 map.put("type",smzhScreenMsg.getType());
		 map.put("content",smzhScreenMsg.getRemakr());
		 list.add(map);

		 if(ObjectUtil.equals(2,smzhScreenMsg.getMsgClass())){//智慧屏公告
			 msgType = MsgConstants.NOTICE_MSG;
		 }else if(ObjectUtil.equals(3,smzhScreenMsg.getMsgClass())){//文化专栏
			 msgType = MsgConstants.CULTURE_MSG;
		 }

		 List<String> projectlist = Arrays.asList(smzhScreenMsg.getProjectNo().split(","));

		 List<Building> buildList= buildingService.queryBuildByProject(projectlist,smzhScreenMsg.getType());

		 List<Building> buildFifterList = buildList;
		 if(ObjectUtil.isNotNull(smzhScreenMsg.getBuildNo())){
			 buildFifterList= buildList.stream()
					 .filter(x-> x.getBuildNo().equals(smzhScreenMsg.getBuildNo()))
					 .collect(Collectors.toList());
		 }

		 if(ObjectUtil.isNotEmpty(smzhScreenMsg.getUnitNo())){
			 buildFifterList= buildFifterList.stream()
					 .filter(x->  x.getUnitNo().equals(smzhScreenMsg.getUnitNo()))
					 .collect(Collectors.toList());
		 }

		 if(ObjectUtil.isNotEmpty(smzhScreenMsg.getRoomNo())){
			 buildFifterList= buildFifterList.stream()
					 .filter(x->  x.getRoomNo().equals(smzhScreenMsg.getRoomNo()))
					 .collect(Collectors.toList());
		 }

		 String finalMsgTyp = msgType;
		 buildFifterList.stream().forEach(x->{
			 //根据操作appId 和项目编号，查询建筑编号，循环推送消息
			 KamliClientUtil.doPostpushMsgUr(x.getUniqueNo(), finalMsgTyp,list);
		 });

		 return Result.OK("推送成功!");
	 }

	 @AutoLog(value = "批量推送智慧屏消息")
	 @ApiOperation(value="批量推送智慧屏消息", notes="批量推送智慧屏消息")
	 @RequestMapping(value = "/batchPush", method = RequestMethod.PUT)
	 public Result<?> batchPush(@RequestBody JSONObject jsonObject) {

		 String ids =  jsonObject.getString("ids");
		 List<String> list1 = Arrays.asList(ids.split(","));
		 list1.stream().forEach(x->{
			 List list = new ArrayList();
			 String msgType = MsgConstants.SCREEN_MSG;
			 SmzhScreenMsg smzhScreenMsg = smzhScreenMsgService.getById(x);
			/* if(ObjectUtil.equals(1,smzhScreenMsg.getType())){

				 Map<String,Object> map = new HashMap<>();
				 map.put("title",smzhScreenMsg.getTitle());
				 map.put("type",smzhScreenMsg.getType());
				 map.put("content",smzhScreenMsg.getContent());
				 list.add(map);

			 }else{*/
				 Map<String,Object> map = new HashMap<>();
				 map.put("title",smzhScreenMsg.getTitle());
				 map.put("type",smzhScreenMsg.getType());
				 map.put("content",smzhScreenMsg.getRemakr());
				 list.add(map);
			 //}

			 if(ObjectUtil.equals(2,smzhScreenMsg.getMsgClass())){//智慧屏公告
				 msgType = MsgConstants.NOTICE_MSG;
			 }else if(ObjectUtil.equals(3,smzhScreenMsg.getMsgClass())){//文化专栏
				 msgType = MsgConstants.CULTURE_MSG;
			 }

			 KamliClientUtil.doPostpushMsgUr(smzhScreenMsg.getBuildNo(),msgType,list);
		 });

		 return Result.OK("推送成功!");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "智慧屏消息表-通过id查询")
	@ApiOperation(value="智慧屏消息表-通过id查询", notes="智慧屏消息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SmzhScreenMsg smzhScreenMsg = smzhScreenMsgService.getById(id);
		if(smzhScreenMsg==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(smzhScreenMsg);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param smzhScreenMsg
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SmzhScreenMsg smzhScreenMsg) {
        return super.exportXls(request, smzhScreenMsg, SmzhScreenMsg.class, "智慧屏消息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SmzhScreenMsg.class);
    }

}
